/*
 * Copyright (c) 2016 JUI All rights reserved.
 */

;(function () {

    /**
     * 分页类
     * @ignore
     * @class
     */
    JUI.Class('Page', {
        /**
         * 构造函数
         * @constructor
         */
        init: function (grid) {
            this.grid = grid;
            this.pageIndex = this.grid.opt('pageNumber');
            this.pageSize = this.grid.opt('pageSize');
            this.total = 0;
            this.pageCount = 0;

            this.pagination = this.grid.opt('pagination');
        }
        , getPageData: function () {
            var data = {};

            data[this.grid.opt('requestPageIndexName')] = this.pageIndex;
            data[this.grid.opt('requestPageSizeName')] = this.pageSize;

            return data;
        }
        , reload: function () {
            this.grid.reload();
        }
        , goPage: function (pageIndex) {
            this.pageIndex = pageIndex;
            this.reload();
        }
        , canFirst: function () {
            return this.pageIndex != 1;
        }
        , first: function () {
            if (this.canFirst()) {
                this.goPage(1);
            }
        }
        , canPre: function () {
            return this.pageIndex > 1;
        }
        , pre: function () {
            if (this.canPre()) {
                this.goPage(this.pageIndex - 1);
            }
        }
        , canNext: function () {
            return this.pageIndex < this.pageCount;
        }
        , next: function () {
            if (this.canNext()) {
                this.goPage(this.pageIndex + 1);
            }
        }
        , canLast: function () {
            return this.pageIndex != this.pageCount && this.pageCount > 0;
        }
        , last: function () {
            if (this.pageIndex != this.pageCount) {
                var pageIndex = this.pageCount;
                this.goPage(pageIndex);
            }
        }
        , setPageSize: function (pageSize) {
            this.pageSize = parseInt(pageSize) || 10;
            this.onChange();
        }
        , onChange: function () {
            this.goPage(1);
        }
        , setPageInfo: function (data) {
            this.total = data[this.grid.opt('serverTotalName')] || 0;
            this.pageCount = calcPageCount(this.pageSize, this.total);
        }
    });

//分页数算法:页数 = (总记录数  +  每页记录数  - 1) / 每页记录数
    function calcPageCount(pageSize, total) {
        return pageSize == 0 ? 1 : parseInt((total + pageSize - 1) / pageSize);
    }

})();